<?php

namespace App\Http\Controllers\Api;

use App\Exceptions\BusinessException;
use App\Models\GoldModel;
use App\Models\UserModel;
use App\Utils\ControllerModelTrait;
use App\Utils\ResponseEnum;
use Carbon\Carbon;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class GoldController extends ApiController
{
    use ControllerModelTrait;

    /**
     * 获取金币列表
     * @param Request $request
     * @return JsonResponse
     */
    public function getList(Request  $request): JsonResponse
    {
        $Model = GoldModel::where('status', 1);
        if ($request->input('uid'))
            $Model = $Model->where('uid', $request->input('uid'));
        if ($request->input('type'))
            $request->input('type') == 1 ? $Model = $Model->where('gold', '>', 0)
                : $Model = $Model->where('gold', '<', 0);
        $paginate = $this->getPagedData($Model, $request);
        return $this->successPaginate($paginate);
    }

    /**
     * 新增金币
     * @param Request $request
     * @return JsonResponse
     * @throws BusinessException
     */
    public function doSave(Request $request): JsonResponse
    {
        $gold = $this->verifyNumeric('gold');
        $username = $this->verifyString('username');
        $uid = UserModel::where('username', trim($username))->value('id');
        GoldModel::create([
            'order_no'  => Carbon::now()->getPreciseTimestamp(3),
            'gold'	    => $gold,
            'status'    => 1,
            'uid'       => $uid,
            'remark'    => '返现'
        ]);
        return $this->success([]);
    }

    /**
     * 提现金币
     * @param Request $request
     * @return JsonResponse|void
     * @throws BusinessException
     */
    public function payBack (Request  $request) {
        $uid = UserModel::where('username', $request->input('username'))->value('id');
        $gold = $this->verifyInteger('gold');
        if ($uid) {
            $total = GoldModel::where('status', 1)->where('uid', $uid)->sum('gold');
            if ($gold > $total || $total <= 0)
                return $this->fail(ResponseEnum::SYSTEM_ERROR);
            GoldModel::create([
                'order_no' => Carbon::now()->getPreciseTimestamp(3),
                'gold'	   => 0 - $gold,
                'status'   => 1,
                'uid'      => $uid,
                'remark'   => '提现'
            ]);
        } else
            return $this->fail(ResponseEnum::CLIENT_DELETED_ERROR);
    }

    /**
     * @param Request $request
     * @return JsonResponse
     */
    public function query(Request  $request): JsonResponse
    {
        if ($request->has('username')) {
            $uid = UserModel::where('username', $request->input('username'))->value('id');
            $gold = GoldModel::where('status', 1)->where('uid', $uid)->sum('gold');
        } else
            $gold = 0;
        return $this->success(['gold' => $gold]);
    }
}
